package com.luomo.java.juc.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author LiuMei
 * @date 2021-04-12.
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyCache cache = new MyCache();

        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                cache.put(String.valueOf(temp + 1), "");
            }, String.valueOf(i + 1)).start();
        }
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                cache.get(String.valueOf(temp + 1));
            }, String.valueOf(i + 1)).start();
        }

    }

}

class MyCache {
    private volatile Map<String, Object> cache = new HashMap<>();
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + "正在写入");
            TimeUnit.SECONDS.sleep(1);
            cache.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public Object get(String key) {
        try {
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + "正在读取");
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName() + "读取完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        return cache.get(key);
    }
}
